import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import axios from 'axios'
import { io, Socket } from 'socket.io-client'
import { useAuthStore } from './auth'

export interface IMessage {
  _id: string
  sender: {
    _id: string
    username: string
    avatar: string
  }
  receiver: {
    _id: string
    username: string
    avatar: string
  }
  content: string
  type: 'text' | 'image'
  read: boolean
  createdAt: string
  updatedAt: string
}

export interface IGroupMessage {
  id: string
  group_id: string
  sender: {
    id: string
    username: string
    avatar: string
  }
  content: string
  type: 'text' | 'image'
  created_at: string
  updated_at: string
}

export interface IChat {
  _id: string
  username: string
  avatar: string
  lastMessage: {
    content: string
    type: string
    createdAt: string
  }
  unreadCount: number
  isGroup?: boolean
  memberCount?: number
}

export interface IGroup {
  id: string
  name: string
  description: string
  group_avatar: string
  invite_code: string
  status: 'active' | 'disbanded'
  disbanded_at?: string
  disbanded_by?: string
  created_at: string
  updated_at: string
  members: {
    user_id: string
    username: string
    avatar: string
    role: 'admin' | 'member'
  }[]
  lastMessage?: {
    content: string
    sender_name: string
    created_at: string
  }
  unreadCount?: number
}

export interface IFriend {
  _id: string
  username: string
  email: string
  avatar: string
  status: 'online' | 'offline'
}

export interface IFriendRequest {
  _id: string
  from: {
    _id: string
    username: string
    email: string
    avatar: string
  }
  status: 'pending' | 'accepted' | 'rejected'
  createdAt: string
}

// 聊天状态管理
export const useChatStore = defineStore('chat', () => {
  const authStore = useAuthStore()

  // WebSocket连接
  const socket = ref<Socket | null>(null)

  // 好友状态
  const friends = ref<IFriend[]>([])
  const friendRequests = ref<IFriendRequest[]>([])

  // 聊天状态
  const chats = ref<IChat[]>([])
  const currentChat = ref<string | null>(null)
  const messages = ref<IMessage[]>([])
  const groupMessages = ref<IGroupMessage[]>([])
  const isTyping = ref(false)
  const typingTimer = ref<number | null>(null)

  // UI状态
  const activeTab = ref<'chats' | 'friends' | 'groups' | 'contacts'>('chats')

  // 计算属性
  const currentChatUser = computed(() => {
    if (!currentChat.value || currentChat.value.startsWith('group_')) return null
    return friends.value.find(f => f._id === currentChat.value) || null
  })

  const unreadMessageCount = computed(() => {
    return chats.value.reduce((acc, chat) => acc + chat.unreadCount, 0)
  })

  // WebSocket连接初始化
  function initSocket() {
    if (socket.value) return

    socket.value = io('/', {
      auth: {
        token: authStore.token
      }
    })

    // 连接成功监听 - 检查待处理的群组加入请求
    socket.value.on('connect', async () => {
      
      
      try {
        // 获取用户的群组列表
        const { data: groups } = await axios.get('/api/groups');
        
        // 遍历每个群组，检查是否有待处理的加入请求（仅对管理员）
        for (const group of groups) {
          if (group.role === 'admin' || group.creator_id === authStore.user?._id) {
            try {
              const { data: requests } = await axios.get(`/api/groups/${group.id}/join-requests`);
              
              if (requests.length > 0) {
                console.log(`🔔 群组"${group.name}"有 ${requests.length} 个待处理的加入请求`);
                
                // 显示Toast通知
                import('vue-toastification').then(({ useToast }) => {
                  const toast = useToast();
                  toast.info(`群组"${group.name}"有 ${requests.length} 个待处理的加入请求`, {
                    timeout: 6000,
                    closeOnClick: true,
                    pauseOnFocusLoss: false,
                    pauseOnHover: true,
                    draggable: true
                  });
                }).catch(() => {
                  console.log(`群组"${group.name}"有 ${requests.length} 个待处理的加入请求`);
                });
              }
            } catch (err) {
              // 如果获取请求失败（可能是权限问题），忽略
              console.log(`无法获取群组"${group.name}"的加入请求`);
            }
          }
        }
      } catch (error) {
        console.error('检查待处理请求失败:', error);
      }
    });

    // 好友状态变更监听
    socket.value.on('userStatusChange', ({ userId, status }) => {
      const index = friends.value.findIndex(f => f._id === userId)
      if (index !== -1) {
        friends.value[index].status = status
      }
    })

    // 私人消息监听
    socket.value.on('privateMessage', ({ senderId, message, possibleDuplicate }) => {
      // 记录消息接收，包括重复标记
      console.log(`收到消息 - 发送者: ${senderId}, 内容: "${message.content}", ${possibleDuplicate ? '可能重复' : '新消息'}`);

      // 如果是当前聊天，直接添加消息（避免重复）
      if (currentChat.value === senderId) {
        // 检查消息是否已存在，避免重复添加
        const messageExists = messages.value.some(msg => msg._id === message._id);
        if (!messageExists) {
          messages.value.push(message);
          console.log(`向聊天添加新消息: ${message._id}`);
        } else {
          console.log(`已忽略重复消息: ${message._id}`);
        }
      } else {
        // 更新未读计数
        // 如果消息可能重复，先检查当前的聊天列表
        if (possibleDuplicate) {
          console.log('收到可能重复的消息，谨慎更新未读计数');
          // 如果是可能重复的消息，不立即刷新聊天列表，而是检查最新的一条消息
          const chat = chats.value.find(c => c._id === senderId);
          if (chat) {
            const lastMsgTime = new Date(chat.lastMessage.createdAt).getTime();
            const thisMsgTime = new Date(message.createdAt).getTime();
            // 只有当收到的消息比最后一条消息新时，才更新未读计数
            if (thisMsgTime > lastMsgTime) {
              fetchChats();
            } else {
              console.log('忽略旧消息的未读计数更新');
            }
          } else {
            // 如果没有现有聊天，需要获取
            fetchChats();
          }
        } else {
          // 如果不是重复消息，直接更新聊天列表
          fetchChats();
        }
      }
    })

    // 群组消息监听
    socket.value.on('groupMessage', ({ groupId, message, possibleDuplicate }) => {
      console.log(`收到群组消息 - 群组: ${groupId}, 内容: "${message.content}"`);

      // 如果是当前聊天的群组，直接添加消息
      if (currentChat.value === `group_${groupId}`) {
        const messageExists = groupMessages.value.some(msg => msg.id === message.id);
        if (!messageExists) {
          groupMessages.value.push(message);
          console.log(`向群聊添加新消息: ${message.id}`);
        } else {
          console.log(`已忽略重复的群聊消息: ${message.id}`);
        }
      } else {
        // 更新未读计数
        // 如果消息可能重复，先检查当前的聊天列表
        if (possibleDuplicate) {
          console.log('收到可能重复的群组消息，谨慎更新未读计数');
          // 如果是可能重复的消息，不立即刷新聊天列表，而是检查最新的一条消息
          const chatId = `group_${groupId}`;
          const chat = chats.value.find(c => c._id === chatId);
          if (chat && chat.lastMessage) {
            // 处理不同格式的时间字段
            const lastMsgTime = new Date(chat.lastMessage.createdAt).getTime();
            const thisMsgTime = new Date(message.created_at || message.createdAt || '').getTime();
            // 只有当收到的消息比最后一条消息新时，才更新未读计数
            if (thisMsgTime > lastMsgTime) {
              fetchChats();
            } else {
              console.log('忽略旧群组消息的未读计数更新');
            }
          } else {
            // 如果没有现有聊天，需要获取
            fetchChats();
          }
        } else {
          // 如果不是重复消息，直接更新聊天列表
          fetchChats();
        }
      }
    })

    // 好友请求监听
    socket.value.on('friendRequest', () => {
      fetchFriendRequests()
    })

    // 好友请求回应监听
    socket.value.on('friendRequestResponse', () => {
      fetchFriends()
      fetchChats()
    })

    // 正在输入状态监听
    socket.value.on('typing', ({ senderId, typing }) => {
      if (currentChat.value === senderId) {
        isTyping.value = typing
      }
    })

    // 群组邀请监听
    socket.value.on('groupInvitation', () => {
      console.log('收到新的群组邀请');
      // 可以在这里添加通知提示
    })

    // 群组加入请求监听
    socket.value.on('groupJoinRequest', (data) => {
      console.log('🔔 收到新的群组加入请求:', data);
      
      // 显示通知提示
      if (data.from && data.from.username) {
        console.log(`👤 ${data.from.username} 申请加入群组 ${data.groupId}`);
        
        // 显示浏览器通知
        if ('Notification' in window && Notification.permission === 'granted') {
          new Notification('新的入群申请', {
            body: `${data.from.username} 申请加入群组`,
            icon: '/favicon.ico'
          });
        }
        
        // 显示Toast通知
        import('vue-toastification').then(({ useToast }) => {
          const toast = useToast();
          toast.info(`${data.from.username} 申请加入群组，请及时处理`, {
            timeout: 5000,
            closeOnClick: true,
            pauseOnFocusLoss: false,
            pauseOnHover: true,
            draggable: true
          });
        }).catch(() => {
          // 如果Toast无法加载，使用alert作为备选
          alert(`新的入群申请：${data.from.username} 申请加入群组`);
        });
      }
    })

    // 群组状态变更监听
    socket.value.on('groupUpdate', ({ groupId }) => {
      console.log(`群组状态更新: ${groupId}`);
      // 如果当前正在查看这个群组，刷新群组详情
      if (currentChat.value === `group_${groupId}`) {
        fetchGroupMessages(groupId);
      }
    })
  }

  // 发送正在输入状态
  function sendTypingStatus(receiverId: string, typing: boolean) {
    if (!socket.value) return

    if (typing) {
      socket.value.emit('typing', { receiverId })
      // 3秒后自动停止输入状态
      if (typingTimer.value) {
        clearTimeout(typingTimer.value)
      }
      typingTimer.value = setTimeout(() => {
        socket.value?.emit('stopTyping', { receiverId })
      }, 3000) as unknown as number
    } else {
      socket.value.emit('stopTyping', { receiverId })
      if (typingTimer.value) {
        clearTimeout(typingTimer.value)
        typingTimer.value = null
      }
    }
  }

  // API 调用函数

  // 获取好友列表
  async function fetchFriends() {
    try {
      const { data } = await axios.get('/api/users/friends')
      friends.value = data
      return true
    } catch (error) {
      console.error('获取好友列表失败', error)
      return false
    }
  }

  // 获取好友请求
  async function fetchFriendRequests() {
    try {
      const { data } = await axios.get('/api/users/friend-requests')
      friendRequests.value = data
      return true
    } catch (error) {
      console.error('获取好友请求失败', error)
      return false
    }
  }

  // 发送好友请求
  async function sendFriendRequest(userId: string) {
    try {
      const { data } = await axios.post('/api/users/friend-requests', { userId })
      return { success: true, message: data.message }
    } catch (error: any) {
      console.error('发送好友请求失败', error)
      return {
        success: false,
        message: error.response?.data?.message || '发送好友请求失败'
      }
    }
  }

  // 响应好友请求
  async function respondToFriendRequest(requestId: string, action: 'accepted' | 'rejected') {
    try {
      const { data } = await axios.put(`/api/users/friend-requests/${requestId}`, { action })

      // 更新好友请求列表
      friendRequests.value = friendRequests.value.filter(req => req._id !== requestId)

      // 如果接受请求，刷新好友列表和聊天列表
      if (action === 'accepted') {
        await Promise.all([
          fetchFriends(),
          fetchChats()
        ])
      }

      return true
    } catch (error) {
      console.error('响应好友请求失败', error)
      return false
    }
  }

  // 搜索用户
  async function searchUsers(keyword: string) {
    try {
      const { data } = await axios.get(`/api/users/search?keyword=${encodeURIComponent(keyword)}`)
      return { success: true, users: data }
    } catch (error) {
      console.error('搜索用户失败', error)
      return { success: false, users: [] }
    }
  }

  // 获取聊天列表
  async function fetchChats() {
    try {
      const { data } = await axios.get('/api/messages/chats/recent')
      chats.value = data
      return true
    } catch (error) {
      console.error('获取聊天列表失败', error)
      return false
    }
  }

  // 获取与特定用户的聊天记录
  async function fetchMessages(userId: string) {
    try {
      // 设置当前聊天对象
      currentChat.value = userId

      // 清空当前消息列表
      messages.value = []

      // 立即更新聊天列表中的未读计数，使红点立即消失
      const chatIndex = chats.value.findIndex(chat => chat._id === userId)
      if (chatIndex !== -1 && chats.value[chatIndex].unreadCount > 0) {
        chats.value[chatIndex].unreadCount = 0
      }

      // 请求历史消息
      const { data } = await axios.get(`/api/messages/${userId}`)

      // 标记消息为已读
      if (data.length > 0) {
        try {
          await axios.put(`/api/messages/${userId}/read`)
        } catch (readError) {
          console.error('标记消息已读失败', readError)
        }
      }

      // 更新消息列表
      messages.value = data
      return true
    } catch (error) {
      console.error('获取消息失败', error)
      return false
    }
  }

  // 获取群组消息
  async function fetchGroupMessages(groupId: string) {
    try {
      // 清空当前群组消息列表
      groupMessages.value = []

      // 立即更新群组聊天列表中的未读计数，使红点立即消失
      const chatId = `group_${groupId}`
      const chatIndex = chats.value.findIndex(chat => chat._id === chatId)
      if (chatIndex !== -1 && chats.value[chatIndex].unreadCount > 0) {
        chats.value[chatIndex].unreadCount = 0
      }

      // 请求群组历史消息
      const { data } = await axios.get(`/api/messages/groups/${groupId}`)

      // 标记群组消息为已读
      if (data.length > 0) {
        try {
          await axios.put(`/api/messages/groups/${groupId}/read`)
        } catch (readError) {
          console.error('标记群组消息已读失败', readError)
        }
      }

      // 更新群组消息列表
      groupMessages.value = data
      return true
    } catch (error) {
      console.error('获取群组消息失败', error)
      return false
    }
  }

  // 发送私人消息
  async function sendMessage(receiverId: string, content: string, type: 'text' | 'image' = 'text') {
    if (!content.trim() && type === 'text') {
      return { success: false, message: '消息内容不能为空' }
    }

    try {
      // 避免重复发送，先将消息添加到本地
      const optimisticMessage = {
        _id: `temp_${new Date().getTime()}`,
        content,
        type,
        sender: {
          _id: authStore.user?._id || '',
          username: authStore.user?.username || '',
          avatar: authStore.user?.avatar || ''
        },
        receiver: {
          _id: receiverId,
          username: friends.value.find(f => f._id === receiverId)?.username || '',
          avatar: friends.value.find(f => f._id === receiverId)?.avatar || ''
        },
        read: false,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
        optimistic: true
      } as IMessage & { optimistic?: boolean }

      // 添加临时消息到UI
      messages.value.push(optimisticMessage)

      // 发送请求
      const { data } = await axios.post('/api/messages', {
        receiverId,
        content,
        type
      })

      // 移除临时消息，添加服务器返回的真实消息
      messages.value = messages.value.filter(m => m._id !== optimisticMessage._id)
      messages.value.push(data)

      // 更新聊天列表
      const chatIndex = chats.value.findIndex(chat => chat._id === receiverId)
      if (chatIndex !== -1) {
        chats.value[chatIndex].lastMessage = {
          content,
          type,
          createdAt: new Date().toISOString()
        }
      } else {
        // 如果是新聊天，刷新聊天列表
        fetchChats()
      }

      return { success: true, message: data }
    } catch (error: any) {
      console.error('发送消息失败', error)

      // 移除临时消息
      messages.value = messages.value.filter(m => !('optimistic' in m))

      return {
        success: false,
        message: error.response?.data?.message || '发送消息失败'
      }
    }
  }

  // 发送群组消息
  async function sendGroupMessage(groupId: string, content: string, type: 'text' | 'image' = 'text') {
    if (!content.trim() && type === 'text') {
      return { success: false, message: '消息内容不能为空' }
    }

    try {
      console.log(`准备发送群组消息 - 群组ID: ${groupId}, 内容: ${content}`);

      // 创建一个临时的乐观消息
      const optimisticMessage = {
        id: `temp_${new Date().getTime()}`,
        group_id: groupId,
        content,
        type,
        sender: {
          id: authStore.user?._id || '',
          username: authStore.user?.username || '',
          avatar: authStore.user?.avatar || ''
        },
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString(),
        optimistic: true
      } as IGroupMessage & { optimistic?: boolean }

      // 添加临时消息到UI
      groupMessages.value.push(optimisticMessage)

      // 发送请求
      console.log(`发送API请求 - POST /api/messages/groups/${groupId}`);
      const response = await axios.post(`/api/messages/groups/${groupId}`, {
        content,
        type
      });

      console.log('服务器响应:', response.data);

      // 移除临时消息
      groupMessages.value = groupMessages.value.filter(m => m.id !== optimisticMessage.id);

      // 适配并添加服务器返回的消息
      // 检查响应格式并适配
      const responseData = response.data;
      const formattedMessage: IGroupMessage = {
        id: responseData.id || responseData._id,
        group_id: groupId,
        content: responseData.content,
        type: responseData.type || 'text',
        sender: {
          id: responseData.sender?.id || responseData.sender?._id || authStore.user?._id || '',
          username: responseData.sender?.username || authStore.user?.username || '',
          avatar: responseData.sender?.avatar || authStore.user?.avatar || ''
        },
        created_at: responseData.created_at || responseData.createdAt || new Date().toISOString(),
        updated_at: responseData.updated_at || responseData.updatedAt || new Date().toISOString()
      };

      console.log('格式化后的消息:', formattedMessage);
      groupMessages.value.push(formattedMessage);

      return { success: true, message: formattedMessage }
    } catch (error: any) {
      console.error('发送群组消息失败:', error);
      console.error('错误详情:', error.response?.data);

      // 移除临时消息
      groupMessages.value = groupMessages.value.filter(m => !('optimistic' in m))

      return {
        success: false,
        message: error.response?.data?.message || '发送群组消息失败'
      }
    }
  }

  // 搜索消息
  async function searchMessages(userId: string, keyword: string) {
    try {
      // 检查是否是群组聊天ID
      if (userId.startsWith('group_')) {
        // 如果是群组聊天，调用群组搜索方法
        const groupId = userId.replace('group_', '');
        return await searchGroupMessages(groupId, keyword);
      }

      // 如果是私聊，使用原来的搜索接口
      const { data } = await axios.get(`/api/messages/${userId}/search?keyword=${encodeURIComponent(keyword)}`);
      return { success: true, messages: data };
    } catch (error) {
      console.error('搜索消息失败', error);
      return { success: false, messages: [] };
    }
  }

  // 搜索群组消息
  async function searchGroupMessages(groupId: string, keyword: string) {
    try {
      const { data } = await axios.get(`/api/messages/groups/${groupId}/search?keyword=${encodeURIComponent(keyword)}`);

      // 格式化群组消息以匹配私聊消息格式，便于前端统一处理
      const formattedMessages = data.map((msg: any) => ({
        _id: msg._id || msg.id,
        sender: {
          _id: msg.sender._id || msg.sender.id,
          username: msg.sender.username,
          avatar: msg.sender.avatar
        },
        receiver: {
          _id: `group_${groupId}`,
          username: '群聊',
          avatar: ''
        },
        content: msg.content,
        type: msg.type,
        read: true,
        createdAt: msg.createdAt || msg.created_at,
        updatedAt: msg.updatedAt || msg.updated_at
      }));

      return { success: true, messages: formattedMessages };
    } catch (error) {
      console.error('搜索群组消息失败', error);
      return { success: false, message: '搜索群组消息失败', messages: [] };
    }
  }

  // 设置当前活动标签
  function setActiveTab(tab: 'chats' | 'friends' | 'groups' | 'contacts') {
    activeTab.value = tab
  }

  // 设置当前聊天
  function setCurrentChat(chatId: string | null) {
    currentChat.value = chatId

    // 如果切换聊天，清空群组消息
    if (chatId && !chatId.startsWith('group_')) {
      groupMessages.value = []
    } else if (!chatId) {
      // 如果关闭聊天，清空所有消息
      messages.value = []
      groupMessages.value = []
    }
  }

  // 初始化数据
  async function initData() {
    initSocket()

    // 清空当前聊天，确保右侧窗口为空
    currentChat.value = null
    messages.value = []
    groupMessages.value = []

    await Promise.all([
      fetchFriends(),
      fetchFriendRequests(),
      fetchChats()
    ])
  }

  // 清理资源
  function cleanup() {
    if (socket.value) {
      socket.value.disconnect()
      socket.value = null
    }
    if (typingTimer.value) {
      clearTimeout(typingTimer.value)
      typingTimer.value = null
    }
  }

  return {
    friends,
    friendRequests,
    chats,
    currentChat,
    messages,
    groupMessages,
    isTyping,
    activeTab,
    currentChatUser,
    unreadMessageCount,
    fetchFriends,
    fetchFriendRequests,
    sendFriendRequest,
    respondToFriendRequest,
    searchUsers,
    fetchChats,
    fetchMessages,
    fetchGroupMessages,
    sendMessage,
    sendGroupMessage,
    searchMessages,
    searchGroupMessages,
    sendTypingStatus,
    setActiveTab,
    setCurrentChat,
    initData,
    cleanup
  }
})